<template>
  <div class="page-user-login">
    <van-nav-bar left-arrow @click-left="$router.back()" title="登录"></van-nav-bar>
    <van-form @submit="onSubmit">
      <van-field v-model="mobile" name="mobile" label="手机号" placeholder="手机号" :rules="[{ pattern: mobilePat, message: '请填写手机号' }]" />
      <van-field v-model="code" name="code" label="验证码" placeholder="验证码" :rules="[
          { required: true, message: '请填写验证码' },
          { validator: validatorCode, message: '验证码6位！' },
        ]">
        <template #button>
          <van-button size="small" type="primary" native-type="button">发送验证码</van-button>
        </template>
      </van-field>
      <div style="margin: 16px;">
        <van-button round block type="info" native-type="submit">提交</van-button>
      </div>
    </van-form>

  </div>
</template>

<script>
import { login } from '@/api/index.js'
import { mapMutations } from 'vuex'
export default {
  name: 'user-chat',
  data () {
    return {
      mobile: '13611111111',
      code: '246810',
      // 正则验证
      mobilePat: /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/
    }
  },
  created () {
    console.log('debugger测试')
  },
  methods: {
    ...mapMutations(['setToken']),
    // 校验函数返回 true 表示校验通过，false 表示不通过
    validatorCode (val) {
      if (val.length !== 6) return false
      return true
    },
    // 提交表单且验证通过后触发 该方法会在执行之前会再次执行所有配置的表单验证
    async onSubmit (values) {
      try {
        // console.log('submit', values)
        const { data } = await login(values)
        this.setToken(data)
        this.$router.push(this.$route.query.redirectUrl || '/user')
        // 提示
        this.$toast.success('登录成功！')
      } catch (error) {
        this.$toast.fail('手机号或验证码错误！')
      }
    }
  }
}
</script>

<style scoped lang='less'></style>
